$(document).ready(function() {
    // 页面加载时获取密码锁状态
    loadPasswordStatus();
    
    // 全局变量用于存储摄像头相关对象
    var videoStream = null;
    var videoElement = null;

    // 图像识别表单提交
    $('#imageForm').on('submit', function(e) {
        e.preventDefault();
        detectShapes();
    });

    // 摄像头表单提交
    $('#cameraForm').on('submit', function(e) {
        e.preventDefault();
        captureImage();
    });

    // 密码检查表单提交
    $('#passwordForm').on('submit', function(e) {
        e.preventDefault();
        checkPassword();
    });

    // 重置密码按钮点击
    $('#resetPasswordBtn').on('click', function() {
        resetPassword();
    });

    // 打开摄像头按钮点击
    $('#startCameraBtn').on('click', function() {
        startCamera();
    });

    // 图像识别函数
    function detectShapes() {
        var formData = new FormData();
        var fileInput = $('#imageInput')[0];
        
        if (fileInput.files.length === 0) {
            alert('请选择一个图像文件');
            return;
        }
        
        formData.append('image', fileInput.files[0]);
        
        $.ajax({
            url: '/detect_shapes',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            beforeSend: function() {
                $('#detectBtn').prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 识别中...');
            },
            success: function(response) {
                if (response.error) {
                    alert('错误: ' + response.error);
                } else {
                    $('#imageResult').html('<img src="data:image/png;base64,' + response.image + '" class="result-image" alt="识别结果">');
                    $('#resultText').text(response.text);
                }
            },
            error: function(xhr, status, error) {
                alert('请求失败: ' + error);
            },
            complete: function() {
                $('#detectBtn').prop('disabled', false).html('<i class="bi bi-search"></i> 识别图形');
            }
        });
    }

    // 拍照识别函数
    function captureImage() {
        if (!videoElement) {
            alert('请先打开摄像头');
            return;
        }
        
        // 创建canvas来捕获当前视频帧
        const canvas = document.createElement('canvas');
        canvas.width = videoElement.videoWidth;
        canvas.height = videoElement.videoHeight;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height);
        
        // 将图像转换为Blob并发送到服务器
        canvas.toBlob(function(blob) {
            const formData = new FormData();
            formData.append('image', blob, 'camera_capture.png');
            
            $.ajax({
                url: '/detect_shapes',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                beforeSend: function() {
                    $('#captureBtn').prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 拍照中...');
                },
                success: function(response) {
                    if (response.error) {
                        alert('错误: ' + response.error);
                    } else {
                        $('#imageResult').html('<img src="data:image/png;base64,' + response.image + '" class="result-image" alt="识别结果">');
                        $('#resultText').text(response.text);
                    }
                },
                error: function(xhr, status, error) {
                    alert('请求失败: ' + error);
                },
                complete: function() {
                    $('#captureBtn').prop('disabled', false).html('<i class="bi bi-camera-fill"></i> 拍照识别');
                }
            });
        }, 'image/png');
    }

    // 打开摄像头
    function startCamera() {
        // 创建video元素
        $('#cameraPreview').html('<video id="cameraVideo" autoplay playsinline style="width: 100%; height: 100%; object-fit: cover;"></video>');
        videoElement = document.getElementById('cameraVideo');
        
        // 请求访问摄像头
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            navigator.mediaDevices.getUserMedia({ video: true })
                .then(function(stream) {
                    videoStream = stream;
                    videoElement.srcObject = stream;
                    $('#startCameraBtn').prop('disabled', true).html('<i class="bi bi-camera-video"></i> 摄像头已开启');
                    $('#captureBtn').prop('disabled', false);
                })
                .catch(function(error) {
                    console.error("无法访问摄像头: ", error);
                    $('#cameraPreview').html('<div class="text-center text-danger" style="display: flex; align-items: center; justify-content: center; height: 100%;"><i class="bi bi-exclamation-circle"></i> 无法访问摄像头: ' + error.message + '</div>');
                    alert('无法访问摄像头: ' + error.message);
                });
        } else {
            $('#cameraPreview').html('<div class="text-center text-danger" style="display: flex; align-items: center; justify-content: center; height: 100%;"><i class="bi bi-exclamation-circle"></i> 浏览器不支持摄像头访问</div>');
            alert('您的浏览器不支持摄像头访问');
        }
    }
    
    // 停止摄像头
    function stopCamera() {
        if (videoStream) {
            const tracks = videoStream.getTracks();
            tracks.forEach(track => track.stop());
            videoStream = null;
        }
        if (videoElement) {
            videoElement.srcObject = null;
            videoElement = null;
        }
    }

    // 检查密码函数
    function checkPassword() {
        var formData = new FormData();
        var fileInput = $('#passwordInput')[0];
        
        if (fileInput.files.length === 0) {
            alert('请选择一个图像文件');
            return;
        }
        
        formData.append('image', fileInput.files[0]);
        
        $.ajax({
            url: '/check_password',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            beforeSend: function() {
                $('#checkPasswordBtn').prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 检查中...');
            },
            success: function(response) {
                if (response.error) {
                    alert('错误: ' + response.error);
                } else {
                    $('#passwordResult').html('<img src="data:image/png;base64,' + response.image + '" class="result-image" alt="输入图形">');
                    
                    // 显示消息
                    var messageDiv = $('#passwordMessage');
                    messageDiv.text(response.message);
                    messageDiv.removeClass('alert-success alert-danger alert-warning');
                    
                    if (response.is_correct && response.is_complete) {
                        messageDiv.addClass('alert-success');
                    } else if (response.is_correct) {
                        messageDiv.addClass('alert-success');
                    } else {
                        messageDiv.addClass('alert-danger');
                    }
                    messageDiv.show();
                    
                    // 更新状态
                    loadPasswordStatus();
                }
            },
            error: function(xhr, status, error) {
                alert('请求失败: ' + error);
            },
            complete: function() {
                $('#checkPasswordBtn').prop('disabled', false).html('<i class="bi bi-check-circle"></i> 检查密码');
            }
        });
    }

    // 重置密码函数
    function resetPassword() {
        $.ajax({
            url: '/reset_password',
            type: 'POST',
            success: function(response) {
                if (response.error) {
                    alert('错误: ' + response.error);
                } else if (response.success) {
                    alert('密码锁已重置');
                    loadPasswordStatus();
                    $('#passwordMessage').hide();
                    $('#passwordResult').html('<p class="text-muted">请上传图像进行密码验证</p>');
                }
            },
            error: function(xhr, status, error) {
                alert('请求失败: ' + error);
            }
        });
    }

    // 加载密码锁状态
    function loadPasswordStatus() {
        $.ajax({
            url: '/password_status',
            type: 'GET',
            success: function(response) {
                if (response.error) {
                    console.error('获取密码状态失败:', response.error);
                    return;
                }
                
                // 更新密码序列显示
                var sequenceHtml = '<h6>当前密码序列:</h6><div class="d-flex">';
                response.sequence.forEach(function(shape, index) {
                    var isCompleted = index < response.current_index;
                    var isActive = index === response.current_index && !response.is_locked;
                    var classes = 'shape-item p-2 m-1 rounded ';
                    
                    if (isCompleted) {
                        classes += 'bg-success text-white';
                    } else if (isActive) {
                        classes += 'bg-warning text-dark';
                    } else {
                        classes += 'bg-light text-muted';
                    }
                    
                    sequenceHtml += '<div class="' + classes + '">' + shape + '</div>';
                });
                sequenceHtml += '</div>';
                $('#sequenceDisplay').html(sequenceHtml);
                
                // 更新状态信息
                var statusHtml = '';
                if (response.is_locked) {
                    var unlockTime = new Date(response.unlock_time * 1000);
                    statusHtml = '<div class="alert alert-danger">系统已锁定，解锁时间: ' + unlockTime.toLocaleString() + '</div>';
                } else if (response.is_complete) {
                    statusHtml = '<div class="alert alert-success">密码验证成功！</div>';
                } else {
                    statusHtml = '<div class="alert alert-info">已识别 ' + response.current_index + ' 个图形</div>';
                }
                $('#passwordStatus').html(statusHtml);
            },
            error: function(xhr, status, error) {
                console.error('获取密码状态失败:', error);
            }
        });
    }
    
    // 页面卸载时停止摄像头
    $(window).on('beforeunload', function() {
        stopCamera();
    });
    
    // 切换标签页时停止摄像头
    $('#image-tab').on('click', function() {
        stopCamera();
        $('#startCameraBtn').prop('disabled', false).html('<i class="bi bi-camera-video"></i> 打开摄像头');
        $('#captureBtn').prop('disabled', true);
        $('#cameraPreview').html('<div class="text-center text-muted" style="display: flex; align-items: center; justify-content: center; height: 100%;"><i class="bi bi-camera-video" style="font-size: 3rem;"></i><p class="mt-2">摄像头预览区域</p></div>');
    });
});